package com.bite.xml_basic_write;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * xmlWriter
 *  修改文件
 *      1)添加    空文档  标签  属性
 *      2)标签的属性  文本内容
 *      3)删除标签
 */
public class Demo3 {
    public static void main(String[] args) throws  Exception {

        //读取xml文件
//        Document doc = new SAXReader()
//                .read(Demo1.class.getClassLoader().getResource("contact.xml"));
        //add();
//        edit();

        Document doc = new SAXReader()
                .read(Demo1.class.getClassLoader().getResource("contact.xml"));

        //删除:获取子标签对象:默认第一个
        Element conElem = doc.getRootElement().element("contact");
        //detach()
//        conElem.detach() ; //自杀


        //方式2;可以通过父标签对象删除子标签对象
        //removeElemnt("子标签");//他杀

        //输出到e盘 :/contact.xml
        OutputStream out = new FileOutputStream("e:/contact.xml") ;
        OutputFormat format = OutputFormat.createPrettyPrint() ;
        XMLWriter writer = new XMLWriter(out,format) ;
        writer.write(doc);
        out.close();
    }

    private static void edit() throws DocumentException, IOException {
        //修改

        Document doc = new SAXReader()
        .read(Demo1.class.getClassLoader().getResource("contact.xml"));

        //获取第一个cotact标签对象
        Element conElem = doc.getRootElement().element("contact");

        Attribute idAttr = conElem.attribute("id");
        //通过属性对象更改属性值  方式1
        idAttr.setValue("003");

        //方式2:添加属性的时候,指定同名属性名称:属性值会被覆盖
        conElem = doc.getRootElement().element("contact");
        //标签对象.setText("str") ;修改指定的标签的文本内容
        conElem.addAttribute("id","004") ;

        //要修改第一个name的文本内容
        Element nameElem = conElem.element("name");
        nameElem.setText("王五");


        //输出到e盘 :/contact.xml
        OutputStream out = new FileOutputStream("e:/contact.xml") ;
        OutputFormat format = OutputFormat.createPrettyPrint() ;
        XMLWriter writer = new XMLWriter(out,format) ;
        writer.write(doc);
        out.close();
    }

    private static void add() throws IOException {
        //1.1 添加空文档
        //DocumentHelper
        Document document = DocumentHelper.createDocument() ;
//        System.out.println(document);
        //添加一个根节点
        Element rootElem = document.addElement("contact-list");
        //在根节点中添加子节点
        Element conElem = rootElem.addElement("contact");
        //给contact标签添加id属性为001
        conElem.addAttribute("id","001") ;
        conElem.addAttribute("name","eric") ;
        conElem.addElement("name") ;


        //输出到e盘 :/contact.xml
        OutputStream out = new FileOutputStream("c:/contact.xml") ;
        OutputFormat format = OutputFormat.createPrettyPrint() ;
        XMLWriter writer = new XMLWriter(out,format) ;
        writer.write(document);
        out.close();
    }
}
